import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectDemo {
    public static void testReflect(){
        try {
            Class<?> c = Class.forName("Student");
            Student student = (Student)c.newInstance();

            Constructor constructor = c.getDeclaredConstructor(String.class, int.class);
            constructor.setAccessible(true);
            Student student1 = (Student) constructor.newInstance("lisi", 22);
            System.out.println(student1);

            Field field = c.getDeclaredField("name");
            field.setAccessible(true);
            field.set(student1, "libai");
            System.out.println(student1);

            Method method = c.getDeclaredMethod("eat");
            method.setAccessible(true);
            method.invoke(student1);

            Method function = c.getDeclaredMethod("function", String.class);
            function.setAccessible(true);
            function.invoke(student1, "Hello, nice to meet you!");

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        ReflectDemo.testReflect();
    }
}
